﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Model.EntityModel;

namespace DataAccess
{
    public static class UserControllerAndDataAccess
    {
        private static bool _isDirectorLogged;
        public static bool IsDirectorLogged { get { return _isDirectorLogged; } }
        private static bool _isPsicologistLogged;
        public static bool IsPsicologistLogged { get { return _isPsicologistLogged; } }
        private static Users _currentLoggedUser;
        public static Users CurrentLoggedUser { get { return _currentLoggedUser; } }

        public static bool IsUserLogged()
        {
            return CurrentLoggedUser != null;
        }

        public static Users RegisterUser(Users newUser)
        {
            BrigadaEntities context = new BrigadaEntities();
            newUser.Password = newUser.Password.GetHashCode().ToString(CultureInfo.InvariantCulture);
            context.AddToUsers(newUser);
            context.SaveChanges();
            return newUser;
        }

        public static bool LogInUser(String username, String password)
        {
            BrigadaEntities context = new BrigadaEntities();
            string passHash = password.GetHashCode().ToString(CultureInfo.InvariantCulture);
            var query = from usr in context.Users
                        where usr.Username == username && usr.Password == passHash
                        select usr;
            var user = query.FirstOrDefault();
            if (user == null)
                return false;
            _currentLoggedUser = user;
            _isDirectorLogged = CurrentLoggedUser.IsDirector;
            if (CurrentLoggedUser.IsPsicologist != null)
                _isPsicologistLogged = CurrentLoggedUser.IsPsicologist == true;
            return true;
        }

        public static bool GrantPermissionFromDirectorAccount(String username, String password)
        {
            BrigadaEntities context = new BrigadaEntities();
            string passHash = password.GetHashCode().ToString(CultureInfo.InvariantCulture);
            var query = from usr in context.Users
                        where usr.Username == username && usr.Password == passHash
                        && usr.IsDirector
                        select usr;
            var user = query.FirstOrDefault();
            return user != null;
        }

        public static void LogOutCurrentUser()
        {
            _currentLoggedUser = null;
            _isDirectorLogged = false;
            _isPsicologistLogged = false;
        }
    }
}
